/*
ESTIMATE FIRST STAGE REGRESSION OF AGE 55 DISCONTINUITY 

Data 	: B1_age55data.dta.
Folder 	: Jonas/data/B1_age55data.dta
Date	: 2018-03-10

Creator		: Jonas Cederlof	(JC)
Description : 
Notes:


LATEST UPDATE: 	2019-10-28

*/

********************************************************************************

clear
set more		 off
cap   log close 	_all

log using 	"../log/B2_firststage.log"	, replace 
use 		 "$datapath/A3_age55data_WC.dta"

*Keeping date at notification 
keep  if eventtime_def==0
replace nottime_def=nottime_def/30

{ // Define globals
*===============================================================================
global covariets 	"C_annual_ear_prenot_def C_female C_immigrant C_tenureatnot C_educ1 C_educ2 C_educ3 "	
global instrument	"treat"
global linear		"runvar inter"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*
{ // Estimate First Stage
*===============================================================================
*==========
xtset   ym_def
*==========
eststo clear
	
*Linear
eststo: reg 	nottime_def  	 $instrument 	$linear  , cluster(varselid)
		test   	$instrument
estadd 	scalar 	Fstat  = r(F), replace
estadd 	local lin   " $ \checkmark $ " 	, replace
estadd 	local quad  " " 		, replace
estadd 	local inter " $ \checkmark $ " 	, replace
estadd 	local covar " "		 	, replace
estadd 	local myfe  " "		 	, replace
estadd 	local disfe " "		 	, replace


eststo: xtreg 	nottime_def  	$instrument 	$linear $covariets 		, cluster(varselid) fe nonest
		test   	$instrument
estadd 	scalar 	Fstat  = r(F), replace
estadd 	local lin   " $ \checkmark $ " 	, replace
estadd 	local quad  " " 		, replace
estadd 	local inter " $ \checkmark $ " 	, replace
estadd 	local covar " $ \checkmark $ "	, replace
estadd 	local myfe  " $ \checkmark $ "	, replace
estadd 	local disfe " "		 	, replace

	xtset varselid	
eststo: xtreg 	nottime_def  	$instrument 	$linear $covariets 	, cluster(varselid) fe nonest
		test   	$instrument
estadd 	scalar 	Fstat  = r(F), replace
estadd 	local lin   " $ \checkmark $ " 	, replace
estadd 	local quad  " " 		, replace
estadd 	local inter " $ \checkmark $ " 	, replace
estadd 	local covar " $ \checkmark $ "	, replace
estadd 	local myfe  " "			, replace
estadd 	local disfe " $ \checkmark $ " 	, replace

*==========
xtset   ym_def
*==========

*Quadratic
eststo: reg 	nottime_def  	$instrument 	$quadratic 			, cluster(varselid)
		test   	$instrument
estadd 	scalar 	Fstat  = r(F), replace
estadd 	local lin   " "		 	, replace
estadd 	local quad  " $ \checkmark $ " 	, replace
estadd 	local inter " $ \checkmark $ " 	, replace
estadd 	local covar " "		 	, replace
estadd 	local myfe  " "		 	, replace
estadd 	local disfe " "		 	, replace

eststo: xtreg 	nottime_def  	$instrument 	$quadratic  $covariets 		, cluster(varselid) fe nonest
		test   	$instrument
estadd 	scalar 	Fstat  = r(F), replace
estadd 	local lin   " " 		, replace
estadd 	local quad  " $ \checkmark $ " 	, replace
estadd 	local inter " $ \checkmark $ " 	, replace
estadd 	local covar " $ \checkmark $ "	, replace
estadd 	local myfe  " $ \checkmark $ "	, replace
estadd 	local disfe "  " 		, replace

	xtset varselid
eststo: xtreg 	nottime_def  	$instrument 	$quadratic  $covariets 		, cluster(varselid) fe nonest
		test   	$instrument	
estadd 	scalar 	Fstat  = r(F), replace
estadd 	local lin   " " 		, replace
estadd 	local quad  " $ \checkmark $ " 	, replace
estadd 	local inter " $ \checkmark $ " 	, replace
estadd 	local covar " $ \checkmark $ "	, replace
estadd 	local myfe  " "			, replace
estadd 	local disfe " $ \checkmark $ " 	, replace


esttab ,  se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) keep($instrument  _cons )

esttab using "$agetablepath/FS/tab_FS.tex", replace keep($instrument _cons ) booktabs nodepvars noobs nomtitles nonumbers ///
varlabels(treat "Above 55" _cons "Control mean") se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) ///
stats(fake lin quad inter covar myfe disfe Fstat r2 N_clust N, fmt(%9.0g %9.0g %9.0g %9.0g %9.0g %9.0g %9.0g  %9.2f %9.3f  %9.0f %9.0fc) /// 
labels("\textit{Polynomial order}" "\quad 1st degree" "\quad 2nd degree" "Interacted w. threshold" "Basline covariates"  "Month/Year FE" "Displacement FE" "F-stat"  "R2" "\# clusters" "\# observations")) ///
title("Effects if MN on advance notice duration, specification analysis  \label{tab:FS}" ) ///
mlabels("(1)" "(2)" "(3)" "(4)" "(5)"  "(6)" ) ///
nonotes 

}
*
{ // First stage graph (binned 2 months)
********************************************************************************

*2 months bins
preserve
	
	gen freq = 1 
	local outcome "nottime_def"
	
	
	*==========
	xtset   ym_def
	*==========

	eststo: xtreg 	`outcome'  	$instrument 	$linear  $covariets 		, cluster(varselid) fe nonest
	local b  = round(_b[$instrument] ,.001)
	local se = round(_se[$instrument] ,.001)
	
	*Residulize year*moth fixed effects
	qui areg `outcome' $covariets if e(sample)==1, absorb(ym_def)
	predict e, residuals
	sum `outcome' 
	replace `outcome' = e + r(mean)
	
	
	gen temp =round(runvar*12)
	egen 	bin = cut(temp), at(-36(2)0)
	egen 	bin2 = cut(temp), at(1(2)37)
	replace bin = bin2 if bin==.
	replace bin = bin + .5 
	bys bin: egen `outcome'_bin = mean(`outcome')
	qui tab runvar bin
	
	
	
	collapse (mean) nottime_def `outcome'_bin (sum) freq, by(runvar bin treat)
	replace runvar = runvar*12

	twoway  (scatter `outcome'_bin bin , ms(o) mcolor(black)) ///
		(lfit    nottime_def runvar [aweight=freq] if treat==0, lcolor(black)) /// 
		(lfit    nottime_def runvar [aweight=freq] if treat==1, lcolor(black)) ///
	, xline( 0 , lcolor(black) lpattern(dash))  legend(off) graphregion(color(white)) ///
	 ytitle("Notification time (months)") xtitle("Normalized age (months)") title("") ///
	 xscale(r(-36 36)) xlab(-36(12)36) name(lfit,replace) ///
	 text(7.5 16   "{&beta}=`b'***" "(0`se')"  ,place(right)  )
	graph export "$agegraphpath/FS/FS_lfit_binned.pdf" ,replace
	/*
	twoway  (scatter `outcome'_bin bin , ms(o) mcolor(black)) ///
		(qfit    nottime_def runvar [aweight=freq] if treat==0, lcolor(black)) /// 
		(qfit    nottime_def runvar [aweight=freq] if treat==1, lcolor(black)) ///
	, xline( 0 , lcolor(black) lpattern(dash))  legend(off) graphregion(color(white)) ///
	 ytitle("Notification time (months)") xtitle("Normalized age (months)") title("") ///
	 xscale(r(-36 36)) xlab(-36(12)36) name(qfit,replace)
	graph export "$agegraphpath/FS/FS_qfit_binned.pdf" ,replace
	*/
restore				
	

}
*
{ // CDF of notification times by runvar
*===============================================================================
preserve
local max = 500
	replace nottime_def=nottime_def*30
	replace runvar= runvar*12
	keep if inrange(runvar,-4,4)
	replace runvar = round(runvar)
	replace nottime_def = `max' if nottime_def >`max'
	
	gen 	newrunvar =runvar
	replace newrunvar = -2.5 if inrange(newrunvar,-3,-2)
	replace newrunvar = 2.5 if inrange(newrunvar,2,3)
	bys newrunvar (nottime_def): cumul nottime_def, gen(blanew)
	tab runvar newrunvar 
	twoway	( line blanew nottime_def  if newrunvar==-4 & nottime_def<`max', lpattern(solid) lcolor(black)  ) ///
		( line blanew nottime_def  if newrunvar==-1 & nottime_def<`max', lpattern(dash) lcolor(black) ) ///
		( line blanew nottime_def  if newrunvar== 1 & nottime_def<`max', lpattern(dash) lcolor(gs7) ) ///
		( line blanew nottime_def  if newrunvar== 4 & nottime_def<`max',lpattern(solid) lcolor(gs7) ) ///
	, ylab(0(.2)1,grid) xlab(0(100)`max',grid) xline( 180 365,lpattern(dash) lstyle(foreground) lcolor(black))  graphregion(color(white)) note("") ///
	xtitle("Notification time") ytitle("CDF") legend(order( 1 "-4"  2 "-1" 3 "1"  4 "4") col(4))
	graph export "$agegraphpath/FS/CDF_allinone_pool.pdf" ,replace
	
restore	
}
*
{ // First stage graph exluding 3 months on each side of cutoff
*===============================================================================

*1 month bin
preserve
	replace nottime_def=nottime_def*30
	replace runvar = round(runvar*12)
	sum runvar
	drop if inrange(runvar,-3,3)
	
	eststo: xtreg 	nottime_def  	$instrument 	$linear  $covariets		, cluster(varselid) fe nonest
	local b  = round(_b[$instrument] ,.001)
	local se = round(_se[$instrument] ,.007)
	
	
	
	*Residulize year*moth fixed effects
	qui areg nottime_def $covariets , absorb(ym_def)
	predict e, residuals
	sum nottime_def 
	replace nottime_def = e + r(mean)
	
	
	
	gen freq = 1 
	collapse (mean) nottime_def (sum) freq, by(runvar treat )
		twoway  (scatter nottime_def runvar, ms(o) mcolor(black)) ///
			(lfit    nottime_def runvar [aweight=freq] if treat==0, lcolor(black)) /// 
			(lfit    nottime_def runvar [aweight=freq] if treat==1, lcolor(black)) ///
		, xline( 0 , lcolor(black) lpattern(dash))  legend(off) graphregion(color(white)) ///
		 ytitle("Notification time (days) ") xtitle("Normalized age (months)") title("")  ///
		 xscale(r(-36 36)) xlab(-36(12)36)  name(a,replace) ///
		 text(225 16   "{&beta}=`b'***" "(`se')"  ,place(right)  )
		graph export "$agegraphpath/FS/FS_lfit_1month_bin_ex3.pdf" ,replace

restore
}
*





log close
